package com.ldy.core.common;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import com.ldy.core.util.MySession;

/**
 * 权限（token）验证
 */
@Component
public class MyAuthorizationInterceptor implements HandlerInterceptor {
	private static final Logger logger = LoggerFactory.getLogger(MyAuthorizationInterceptor.class);

	@Value("${server.security.enabled:true}")
	private boolean security;
	
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
    	String path = request.getServletPath();
        logger.info(path);
        if (!security) {
        	return true;
        }
        // 从请求头获取token
        String token = request.getHeader(Constant.TOKEN_KEY);

        // 如果请求头没有token,则从请求参数中取
        if (StringUtils.isEmpty(token)) {
            token = request.getParameter(Constant.TOKEN_KEY);
        }
        // 如果还是没有token,则抛异常
        if (StringUtils.isEmpty(token)) {
           throw new LoginException(Constant.TOKEN_NULL);
        }

        // 查询token信息
        LoginUser loginUser = MySession.get(token);
        if (null == loginUser) {
        	throw new LoginException(Constant.TOKEN_ERROR);
        }
        // 延长token时效
        MySession.reset(token, loginUser);
        return true;
    }
}